<template>
  <div class="admin-container">
    <!-- 搜索卡片 -->
    <div class="search-card">
      <el-form :model="searchForm" label-width="100px" class="search-form">
        <div class="search-grid">
          <el-form-item label="用户昵称">
            <el-input v-model="searchForm.nickname" placeholder="请输入用户昵称" prefix-icon="User" clearable
              style="width: 200px;" />
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="searchForm.mobile" placeholder="请输入手机号码" prefix-icon="Phone" clearable
              style="width: 200px;" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" style="width: 200px;" clearable>
              <el-option label="全部" value="" />
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getLists" :icon="Search">
              搜索
            </el-button>
            <el-button @click="resetSearch" :icon="RefreshRight" plain>
              重置
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 表格卡片 -->
    <div class="table-card">
      <div class="table-header">
        <div class="table-title">
          <el-icon>
            <UserFilled />
          </el-icon>
          <span>用户列表</span>
          <el-tag type="info" size="small">{{ pager.total }} 条记录</el-tag>
        </div>
      </div>

      <!-- 现代化表格 -->
      <el-table :data="lists" style="width: 100%" empty-text="暂无数据" class="modern-table"
        :header-cell-style="{ background: '#f9fafb', color: '#374151', fontWeight: 600 }" v-loading="loading">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="用户昵称" prop="nickname" />
        <el-table-column label="用户头像" prop="avatar">
          <template v-slot="scope">
              <el-image shape="square" preview-teleported class="w-8 h-8" :src="scope.row.avatar" :previewSrcList="[scope.row.avatar]" ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" prop="mobile" />
        <el-table-column label="用户类型" prop="user_type">
          <template v-slot="scope">
            <el-tag v-if="scope.row.user_type === 1">微信小程序用户</el-tag>
            <el-tag v-else>其他用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="changeEdit(scope.row)"
              active-text="启用" inactive-text="禁用" inline-prompt />
          </template>
        </el-table-column>
        <el-table-column label="更新日期" prop="updated_at" />
        <el-table-column label="注册时间" width="180" align="center">
          <template #default="scope">
            <div class="time-info">
              <div>{{ formatDate(scope.row.created_at) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(scope.row)"  >编辑</el-button>
              <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.row)" >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background v-model:current-page="pager.page" v-model:page-size="pager.page_size"
          layout="total, sizes, prev, pager, next, jumper" :total="pager.total" :page-sizes="[10, 30, 50, 100]"
          @current-change="handleCurrentChange" @size-change="getLists" />
      </div>
    </div>
  </div>
  <edit ref="editRef" @success="getLists" />
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { getUserListsApi, deleteUserApi, updateUserApi } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search, RefreshRight, UserFilled } from '@element-plus/icons-vue'
import edit from './edit.vue'

const editRef = ref()
const loading = ref(false)

const lists = ref([])

const searchForm = ref<any>({
  nickname: '',
  mobile: '',
  status: '',
})

const pager = reactive<any>({
  page: 1,
  page_size: 10,
  total: 0,
})

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getLists = async () => {
  loading.value = true
  try {
    const { data } = await getUserListsApi({
      nickname: searchForm.value.nickname,
      mobile: searchForm.value.mobile,
      status: searchForm.value.status,
      page: pager.page,
      page_size: pager.page_size,
    })
    lists.value = data.list || []
    pager.total = data.total || 0
    pager.page_size = data.per_page || 10
    pager.page = data.current_page || 1
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  editRef.value.open('add')
  editRef.value.setFormData()
}

const handleEdit = (row: any) => {
  editRef.value.open('edit')
  editRef.value.setFormData(row)
}

const handleDelete = async (row: any) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteUserApi({ id: row.id }).then(() => {
      ElMessage.success('删除成功')
      getLists()
    })
  })
}

const changeEdit = async (row: any) => {
  await updateUserApi(row)
  ElMessage.success('状态更新成功')
  getLists()
}

const resetSearch = () => {
  searchForm.value = {
    nickname: '',
    mobile: '',
    status: '',
  }
  getLists()
}

const handleCurrentChange = (val: number) => {
  pager.page = val
  getLists()
}

getLists()
</script>

<style scoped>
.admin-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 搜索卡片 */
.search-card {
  background: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
}

.search-header {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.search-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 3px;
  align-items: flex-end;
}

/* 表格卡片 */
.table-card {
  background: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-header {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

/* 现代化表格 */
.modern-table {
  flex: 1;
}

:deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

:deep(.el-table__body-wrapper) {
  border-radius: 0 0 8px 8px;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #e5e7eb;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 1px;
}

.nickname {
  font-weight: 600;
  color: #111827;
  font-size: 13px;
}

.account {
  font-size: 11px;
  color: #6b7280;
}

/* 时间信息样式 */
.time-info {
  text-align: center;
}

.time-label {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 2px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

/* 分页样式 */
.pagination-container {
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-grid {
    grid-template-columns: 1fr;
  }

  .search-actions {
    justify-content: flex-end;
  }
}
</style>
